package com.tedu.day08springmvc.controller;


import com.tedu.day08springmvc.mapper.UserMapper;
import com.tedu.day08springmvc.pojo.dto.UserDTO;
import com.tedu.day08springmvc.pojo.entity.User;
import com.tedu.day08springmvc.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

//@Controller
//@ResponseBody
//@RestController  使用 @RestController 后会自动将返回值转换为json格式，
// 下面的方法就不需要再写@ResponseBody了
@RestController
public class UserController {

    @Autowired
    private UserMapper userMapper;

    //@RequestMapping("/users/reg")
    @PostMapping("/users/reg")
    @ResponseBody
    public String regUser(UserDTO userDTO){
        System.out.println("userDTO"+userDTO);
        User user = new User();
        System.out.println("user:"+user);
        BeanUtils.copyProperties(userDTO,user);
        System.out.println("user:"+user);
        user.setCreated(new Date());

        int num=userMapper.insertUser(user);
        return num>0?"注册成功":"注册失败";
    }


    //@RequestMapping("/users/delete",method = Requ)
    @DeleteMapping("/users/delete/{id}")
    @ResponseBody
    public String deleteUser(@PathVariable Integer id){
        System.out.println("delect_id:"+id);
        int num=userMapper.deleteUser(id);
        return num>0?"删除成功":"删除失败";
    }

    //@RequestMapping(value = "/users/update",method = RequestMethod.PUT)
    @PutMapping("/users/update")
    @ResponseBody
    public String updateUser(UserDTO userDTO){
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        //
        int num=userMapper.updateUser(user);
        return num>0?"修改成功":"修改失败";
    }

    //@RequestMapping(value = "/users/find" ,method = RequestMethod.GET)
    @GetMapping("/users/find")
    @ResponseBody
    public List<UserVO> findUser(){
        //直接将UserMapper中查询出来的集合返回即可
        return userMapper.findAllUser();
    }


    @GetMapping("/users/findById/{id}")
    public UserVO findById(@PathVariable int id){

        return userMapper.findUserVOById(id);
    }

}
